package com.sxx.mallAuth.controller;

import com.alibaba.fastjson.JSON;
import com.sxx.commons.constant.AuthConstant;
import com.sxx.commons.utils.HttpUtils;
import com.sxx.commons.utils.R;
import com.sxx.commons.vo.MemberVO;
import com.sxx.mallAuth.feign.MemberFeignService;
import com.sxx.mallAuth.vo.SocialUser;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;

/**
 * @Auther: sunxx
 * @Date: 2024/8/18 - 08 - 18 - 19:05
 * @Description: com.sxx.mallAuth.controller
 * @version: 1.0
 */
@Controller
public class OAuth2Controller {

    @Autowired
    private MemberFeignService memberFeignService;

    @RequestMapping("/oauth/weibo/success")
    public String weiboOAuth(@RequestParam("code") String code,
                             HttpSession session) throws Exception {
        Map<String, String> body = new HashMap<>();
        body.put("client_id", "4183983711");
        body.put("client_secret", "92c07a5d3c5dc446ebe542bf8263b3ba");
        body.put("grant_type", "authorization_code");
        body.put("redirect_uri", "http://auth.jiaxuanmall.asia:8051/oauth/weibo/success");//
        body.put("code", code);
        // 根据Code获取对应的Token信息
        HttpResponse post = HttpUtils.doPost("https://api.weibo.com"
                , "/oauth2/access_token"
                , "post"
                , new HashMap<>()
                , null
                , body
        );
        int statusCode = post.getStatusLine().getStatusCode();
        if (statusCode != 200) {
            // 说明获取Token失败,就调回到登录页面
            return "redirect:http://auth.jiaxuanmall.asia:8051/login.html";
        }
        // 说明获取Token信息成功
        String json = EntityUtils.toString(post.getEntity());
        SocialUser socialUser = JSON.parseObject(json, SocialUser.class);
        R r = memberFeignService.login(socialUser);
        if (r.getCode() != 0){
            return "redirect:http://auth.jiaxuanmall.asia:8051/login.html";
        }
        String entityJSON = (String)r.get("entity");
        //System.out.println("------------>"+entityJSON);
        MemberVO memberVO = JSON.parseObject(entityJSON, MemberVO.class);
        session.setAttribute(AuthConstant.AUTH_SESSION_REDIS,memberVO);
        // 注册成功就需要调整到商城的首页
        return "redirect:http://jiaxuanmall.asia:8070/home";
    }
}